import 'package:dailoz/main.dart';
import 'package:dailoz/utils/toast.dart';
import 'package:dailoz/views/login.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';

class AppException {
  static void formatError(DioError error) {
    BuildContext? context = navigatorKey.currentState?.overlay?.context;
    DioErrorType errorType = error.type;
    switch (errorType) {
      case DioErrorType.connectionTimeout:
        {
          showToast("连接超时");
        }
        break;
      case DioErrorType.sendTimeout:
        {
          showToast("请求超时");
        }
        break;
      case DioErrorType.receiveTimeout:
        {
          showToast("响应超时");
        }
        break;
      case DioErrorType.badResponse:
        {
          try {
            int? errCode = error.response!.statusCode;
            switch (errCode) {
              case 400:
                {
                  showToast("请求语法错误");
                }
                break;
              case 401:
                {
                  showToast("对不起，您的登录已过期，请重新登录");
                  Navigator.of(context!).pushNamedAndRemoveUntil(
                    Login.id,
                    (Route<dynamic> route) => false,
                  );
                }
                break;
              case 444:
                {
                  showToast("用户不存在");
                }
                break;
              case 403:
                {
                  showToast("服务器拒绝执行");
                }
                break;
              case 404:
                {
                  showToast("无法连接服务器");
                }
                break;
              case 405:
                {
                  showToast("请求方法被禁止");
                }
                break;
              case 500:
                {
                  showToast("服务器内部错误");
                }
                break;
              case 502:
                {
                  showToast("无效的请求");
                }
                break;
              case 503:
                {
                  showToast("服务器挂了");
                }
                break;
              case 505:
                {
                  showToast("不支持HTTP协议请求");
                }
                break;
              default:
                {
                  showToast(error.response?.data['message']);
                }
            }
          } catch (e) {
            showToast("${error.response?.statusCode} 未知错误");
          }
        }
        break;
      case DioErrorType.cancel:
        {
          showToast("请求取消");
        }
        break;
      default:
        {
          showToast("网络未连接，请检查网络");
        }
    }
  }
}
